package com.atguigui.leetcode;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 919.完全二叉树插入器
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/7/25 23:07
 */
public class P919CompleteBinaryTreeInserter {
    public static void main(String[] args) {
        TreeNode node = new P919CompleteBinaryTreeInserter().new TreeNode(0);
        CBTInserter solution = new P919CompleteBinaryTreeInserter().new CBTInserter(node);
        // TO TEST
    }

    class CBTInserter {

        Queue<TreeNode> candidate;
        TreeNode root;

        /**
         * 初始化
         *
         * @param root
         */
        public CBTInserter(TreeNode root) {
            candidate = new ArrayDeque<TreeNode>();
            this.root = root;

            Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
            queue.offer(root);

            //将原树遍历存放到队列中
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                //左右都为null
                if (!(node.left != null && node.right != null)) {
                    //可以插入数据的节点
                    candidate.offer(node);
                }
            }
        }

        public int insert(int val) {
            TreeNode child = new TreeNode(val);
            TreeNode node = candidate.peek();
            int ret = node.val;
            if (node.left == null) {
                node.left = child;
            } else {
                node.right = child;
                candidate.poll();
            }
            candidate.offer(child);
            return ret;
        }

        public TreeNode get_root() {
            return root;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
